const path = require('path')
const fs = require('fs')
const qrcode = require('qrcode')

const {
    getUserInfo,
} = require('../service/user.service')

const {
    createActivity,
    deleteByActId,
    modifyByActId,
    getActInfo,
    getACtDetailById,
} = require('../service/activity.service')
const { addActivityImg, getActivityImg, getAllActivityImg } = require('../service/activityImg.service')

const { createFeedback, getFeedbackList, handleFeedback } = require('../service/userFeedback.service')

const { getEntryInfo, createEntry, modifyEntry } = require('../service/entryDocuments.service')

const { addactSignScore, deleteactSignScore } = require('../service/actSignScore.service')

const { formatDate } = require('../utils/formatData')
class activityController {
    /**
     * 创建活动
     */
    async createACT (ctx, next) {
        const {
            actTitle: act_title,
            actContent: act_content,
            actType: act_type,
            signType: sign_type,
            organizerAccount: organizer_account,
            teacherAccount: teacher_account,
            applyDesc: apply_desc,
            startTime: start_time,
            endTime: end_time,
            signScoreList
        } = ctx.request.body

        const imgList = ctx.request.files ? ctx.request.files.actImg : ''
        const imgListIsArray = imgList instanceof Array
        // 写入数据
        try {
            const actRes = await createActivity({ act_title, act_content, act_type, sign_type, organizer_account, teacher_account, apply_desc, start_time, end_time })
            if (actRes.errorFlag) {
                // 创建失败，删除上传的图片
                if (imgList) {
                    if (!imgListIsArray) {
                        fs.unlink(imgList.filepath, (err) => {
                            if (err) {
                                // 找不到旧图像路径
                                console.error('找不到该图片', err)
                            }
                        })
                    } else {
                        imgList.forEach((item) => {
                            fs.unlink(item.filepath, (err) => {
                                if (err) {
                                    // 找不到旧图像路径
                                    console.error('找不到该图片', err)
                                }
                            })
                        })
                    }
                }
                console.error('活动创建失败，活动表数据库新增数据错误', actRes.message)
                ctx.status = 500
            } else {
                // 创建活动成功，图片路径导入数据库表
                let imgAddflag = true
                if (imgListIsArray) {
                    for (const item of imgList) {
                        const img_path = 'activity/' + path.basename(item.filepath)
                        const imgRes = await addActivityImg({ img_path, act_id: actRes.act_id })
                        if (imgRes.errorFlag) {
                            // 创建失败，删除上传的图片
                            imgAddflag = false
                            fs.unlink(item.filepath, (err) => {
                                if (err) {
                                    // 找不到旧图像路径
                                    console.error('找不到该图片', err)
                                }
                            })
                            // 然后删除已经创建的活动
                            await deleteByActId(actRes.act_id)
                            console.error('活动创建失败，活动图片表数据库新增数据错误', imgRes.message)
                            ctx.status = 500
                        }
                    }
                } else {
                    if (imgList) {
                        const img_path = 'activity/' + path.basename(imgList.filepath)
                        const imgRes = await addActivityImg({ img_path, act_id: actRes.act_id })
                        if (imgRes.errorFlag) {
                            // 创建失败，删除上传的图片
                            imgAddflag = false
                            fs.unlink(imgList.filepath, (err) => {
                                if (err) {
                                    // 找不到旧图像路径
                                    console.error('找不到该图片', err)
                                }
                            })
                            // 然后删除已经创建的活动
                            await deleteByActId(actRes.act_id)
                            console.error('活动创建失败，活动图片表数据库新增数据错误', imgRes.message)
                            ctx.status = 500
                        }
                    }
                }

                // 创建活动成功，将签到加分录入数据库
                if (sign_type == '0' || sign_type == '1') {
                    // 获取加分类型数组，循环存入活动分数表
                    let scoreList = JSON.parse(signScoreList)
                    for (const item of scoreList) {
                        const res = await addactSignScore({ act_id: actRes.act_id, score: item.score, score_type: item.scoreType })
                    }

                }

                // 创建活动成功，生成二维码
                if (sign_type == '0') {
                    console.log(actRes)
                    let qrCodeObj = {}
                    qrCodeObj.url = '/pages/sign/sign' // 活动扫码签到页面
                    qrCodeObj.actId = actRes.act_id

                    qrcode.toFile(`./src/public/upload/qrCode/${actRes.act_id}.png`, JSON.stringify(qrCodeObj), {
                        color: {
                            dark: '#000', // 颜色深色部分
                            light: '#fff' // 颜色浅色部分
                        },
                        errorCorrectionLevel: 'H', // 错误纠正等级
                        width: 400 // 二维码尺寸
                    }, function (err) {
                        if (err) throw err
                        console.log('done')
                    })
                }

                if (imgAddflag) {
                    ctx.status = 200
                    ctx.body = {
                        hasOk: true,
                        code: 20000,
                        message: '活动创建成功，请等待上级审批',
                        data: {
                            actTitle: actRes.act_title,
                        }
                    }
                }
            }
        } catch (error) {
            // 创建失败，删除上传的图片
            if (imgList) {
                if (!imgListIsArray) {
                    fs.unlink(imgList.filepath, (err) => {
                        if (err) {
                            // 找不到旧图像路径
                            console.error('找不到该图片', err)
                        }
                    })
                } else {
                    imgList.forEach((item) => {
                        fs.unlink(item.filepath, (err) => {
                            if (err) {
                                // 找不到旧图像路径
                                console.error('找不到该图片', err)
                            }
                        })
                    })
                }
            }
            ctx.status = 500
            console.error('创建失败', error)
            return
        }
    }

    /**
     * 修改活动
     */
    async editACT (ctx, next) {
        const {
            actId,
            actTitle: act_title,
            actContent: act_content,
            applyDesc: apply_desc,
            startTime: start_time,
            endTime: end_time,
            signScoreList
        } = ctx.request.body
        try {
            const res = await modifyByActId({ approval_status: 0, act_title, act_content, apply_desc, start_time, end_time }, actId)
            let scoreList = JSON.parse(signScoreList)
            await deleteactSignScore(actId)
            for (const item of scoreList) {
                const res = await addactSignScore({ act_id: actId, score: item.score, score_type: item.scoreType })
            }
            if (res.errorFlag) {
                console.error('修改失败，数据库错误', res.message)
                ctx.status = 500
            } else {
                ctx.status = 200
                ctx.body = {
                    hasOk: true,
                    code: 20000,
                    message: '活动修改成功',
                    data: ''
                }
            }
        } catch (error) {
            console.log(error)
        }
    }

    /**
     * 审批活动
     */
    async approvalACT (ctx, next) {
        const { actId, approvalStatus, approvalDesc } = ctx.request.body
        try {
            const res = await modifyByActId({ approval_status: approvalStatus, approval_desc: approvalDesc }, actId)
            if (res.errorFlag) {
                console.error('审批失败，数据库错误', res.message)
                ctx.status = 500
            } else {
                ctx.status = 200
                ctx.body = {
                    hasOk: true,
                    code: 20000,
                    message: '活动审批成功',
                    data: ''
                }
            }
        } catch (error) {
            ctx.status = 500
            console.error('数据修改失败', error)
            return
        }
    }

    /**
     * 按传入值的需求获取活动
     */
    async getACTList (ctx, next) {
        try {
            const { actId, approvalStatus, actTitle, teacherAccount, organizerAccount, actType, scoreApprovalStatus, endTime } = ctx.query
            let { offect, limit } = ctx.query
            offect = limit * offect - limit
            let actListRes = []

            let time = ''
            if (endTime) {
                // 传入endTime为1，则取已经结束的活动
                time = formatDate(new Date())
            }

            // 如果传入的值存在，则按照传入值索引
            const { count, rows } = await getActInfo({
                act_id: actId,
                approval_status: approvalStatus,
                act_title: actTitle,
                teacher_account: teacherAccount,
                organizer_account: organizerAccount,
                act_type: actType,
                approval_status: approvalStatus,
                score_approval_status: scoreApprovalStatus,
                time: time,
                offect,
                limit
            })
            actListRes = rows
            let resList = []
            for (let item of actListRes) {
                let tempObj = {}
                tempObj.id = item.id
                tempObj.actId = item.act_id
                tempObj.actTitle = item.act_title
                tempObj.actContent = item.act_content

                const res = await getActivityImg({ act_id: item.act_id })
                let imgList = []
                res.forEach(item => {
                    let imgObj = {}
                    imgObj.id = item.id
                    imgObj.imgPath = item.img_path
                    imgObj.actId = item.act_id
                    imgList.push(imgObj)
                })
                tempObj.imgPath = imgList

                tempObj.actType = item.act_type
                if (item.act_type === 0) {
                    tempObj.actTypeDetail = '活动'
                } else if (item.act_type === 1) {
                    tempObj.actTypeDetail = '比赛'
                }

                tempObj.signType = item.sign_type
                if (item.sign_type === 0) {
                    tempObj.signTypeDetail = '扫码签到'
                } else if (item.sign_type === 1) {
                    tempObj.signTypeDetail = '定位签到'
                } else if (item.sign_type === 2) {
                    tempObj.signTypeDetail = '提交参赛文件'
                }

                tempObj.organizerAccount = item.organizer_account
                const organizerRes = await getUserInfo({ user_account: tempObj.organizerAccount })
                const organizerDataValues = organizerRes[0].dataValues
                tempObj.organizerName = organizerDataValues.user_name

                tempObj.teacherAccount = item.teacher_account
                const teacherRes = await getUserInfo({ user_account: tempObj.teacherAccount })
                const teacherDataValues = teacherRes[0].dataValues
                tempObj.teacherName = teacherDataValues.user_name

                tempObj.applyDesc = item.apply_desc
                tempObj.approvalDesc = item.approval_desc
                tempObj.startTime = formatDate(Date.parse(item.start_time))
                tempObj.endTime = formatDate(Date.parse(item.end_time))

                tempObj.approvalStatus = item.approval_status
                switch (item.approval_status) {
                    case 0:
                        tempObj.approvalStatusDetail = '未审批'
                        break
                    case 1:
                        tempObj.approvalStatusDetail = '审批通过'
                        break
                    case 2:
                        tempObj.approvalStatusDetail = '审批驳回'
                }

                tempObj.createdAt = item.createdAt
                tempObj.updatedAt = item.updatedAt
                resList.push(tempObj)
            }
            ctx.status = 200
            ctx.body = {
                hasOk: true,
                code: 20000,
                data: {
                    resList,
                    count: count
                }
            }
        } catch (error) {
            console.log(error)
        }
    }

    /**
     * 按传入值的活动id获取活动
     */
    async getACTInfoById (ctx, next) {
        const { actId } = ctx.query
        // let actListRes = []
        // 如果传入的值存在，则按照传入值索引
        const actListRes = await getACtDetailById(actId)

        let actObj = {}
        actObj.id = actListRes.id
        actObj.actId = actListRes.act_id
        actObj.actTitle = actListRes.act_title
        actObj.actContent = actListRes.act_content

        actObj.actType = actListRes.act_type
        if (actListRes.act_type === 0) {
            actObj.actTypeDetail = '活动'
        } else if (actListRes.act_type === 1) {
            actObj.actTypeDetail = '比赛'
        }

        actObj.signType = actListRes.sign_type
        if (actListRes.sign_type === 0) {
            actObj.signTypeDetail = '扫码签到'
        } else if (actListRes.sign_type === 1) {
            actObj.signTypeDetail = '定位签到'
        } else if (actListRes.sign_type === 2) {
            actObj.signTypeDetail = '提交参赛文件'
        }


        actObj.organizerAccount = actListRes.organizer_account
        const organizerRes = await getUserInfo({ user_account: actObj.organizerAccount })
        const organizerDataValues = organizerRes[0].dataValues
        actObj.organizerName = organizerDataValues.user_name

        actObj.teacherAccount = actListRes.teacher_account
        const teacherRes = await getUserInfo({ user_account: actObj.teacherAccount })
        const teacherDataValues = teacherRes[0].dataValues
        actObj.teacherName = teacherDataValues.user_name

        actObj.applyDesc = actListRes.apply_desc
        actObj.scoreApprovalStatus = actListRes.score_approval_status
        actObj.approvalDesc = actListRes.approval_desc
        actObj.startTime = formatDate(Date.parse(actListRes.start_time))
        actObj.endTime = formatDate(Date.parse(actListRes.end_time))

        actObj.approvalStatus = actListRes.approval_status
        switch (actListRes.approval_status) {
            case 0:
                actObj.approvalStatusDetail = '未审批'
                break
            case 1:
                actObj.approvalStatusDetail = '审批通过'
                break
            case 2:
                actObj.approvalStatusDetail = '审批驳回'
        }

        actObj.createdAt = actListRes.createdAt
        actObj.updatedAt = actListRes.updatedAt
        ctx.status = 200
        ctx.body = {
            hasOk: true,
            code: 20000,
            data: actObj
        }
    }

    /**
     * 按照活动Id获取该活动所有图片
     */
    async getACTImgById (ctx, next) {
        const { actId } = ctx.query
        const res = await getActivityImg({ act_id: actId })
        let imgList = []
        res.forEach(item => {
            let imgObj = {}
            imgObj.id = item.id
            imgObj.imgPath = item.img_path
            imgObj.actId = item.act_id
            imgList.push(imgObj)
        })
        if (res.errorFlag) {
            console.error('图片获取失败失败，数据库错误', res.message)
            ctx.status = 500
        } else {
            ctx.status = 200
            ctx.body = {
                hasOk: true,
                code: 20000,
                message: '图片获取成功',
                data: imgList
            }
        }
    }

    /**
     * 获取活动所有图片
     */
    async getAllACTImg (ctx, next) {
        try {
            let { limit } = ctx.query

            const { rows } = await getActInfo({ approval_status: 1 })
            let actIdList = []
            rows.forEach(item => {
                actIdList.push(item.act_id)
            })

            const res = await getAllActivityImg(actIdList)

            let obj = {}
            let newArr = res.reduce(function (preValue, item) {
                obj[item.act_id] ? '' : obj[item.act_id] = true && preValue.push(item)
                return preValue
            }, [])
            limit ? limit = limit * 1 : limit = 5
            newArr.splice(limit, 100)
            let imgList = []
            newArr.forEach(item => {
                let imgObj = {}
                imgObj.id = item.id
                imgObj.imgPath = item.img_path
                imgObj.actId = item.act_id
                imgList.push(imgObj)
            })
            if (res.errorFlag) {
                console.error('图片获取失败失败，数据库错误', res.message)
                ctx.status = 500
            } else {
                ctx.status = 200
                ctx.body = {
                    hasOk: true,
                    code: 20000,
                    message: '图片获取成功',
                    data: imgList
                }
            }
        } catch (error) {
            console.log(error)
        }
    }

    /**
     * 增加活动反馈
     */
    async createFeedback (ctx, next) {
        const { userAccount, actId, feedback } = ctx.request.body
        // 写入数据
        try {
            const res = await createFeedback({ user_account: userAccount, act_id: actId, feedback })
            if (res.errorFlag) {
                console.error('创建失败，数据库新增数据错误', res.message)
                ctx.status = 500
            } else {
                ctx.status = 200
                ctx.body = {
                    hasOk: true,
                    code: 20000,
                    message: '反馈已提交，请等待处理',
                    data: {
                        id: res.id,
                        feedbackId: res.feedback_id,
                        feedback: res.feedback
                    }
                }
            }
        } catch (error) {
            console.error('反馈新增失败', error)
            ctx.app.emit('error', roleAddError, ctx)
            return
        }
    }

    /**
     * 获取活动反馈列表
     */
    async getFeedbackList (ctx, next) {
        const { actId, isHandled, userAccount, organizerAccount } = ctx.query
        const res = await getFeedbackList({ act_id: actId, is_handled: isHandled, user_account: userAccount })
        if (res.errorFlag) {
            console.error('反馈获取失败失败，数据库错误', res.message)
            ctx.status = 500
        } else {
            let tempList = []
            for (let item of res) {
                let tempObj = {}
                const actRes = await getACtDetailById(item.act_id)
                tempObj.feedbackId = item.feedback_id
                tempObj.userAccount = item.user_account
                const userRes = await getUserInfo({ user_account: userAccount })
                const userDataValues = userRes[0].dataValues
                tempObj.userName = userDataValues.user_name
                tempObj.actId = item.act_id
                tempObj.feedback = item.feedback
                tempObj.isHandled = item.is_handled
                tempObj.handleOpinion = item.handle_opinion
                tempObj.organizerAccount = actRes.organizer_account
                tempObj.actTitle = actRes.act_title
                tempList.push(tempObj)
            }
            let resList = []
            if (organizerAccount) {
                resList = tempList.filter(item => organizerAccount === item.organizerAccount)
            } else if (userAccount) {
                resList = tempList.filter(item => userAccount === item.userAccount)
            } else {
                resList = tempList
            }

            ctx.status = 200
            ctx.body = {
                hasOk: true,
                code: 20000,
                message: '反馈获取成功',
                data: resList
            }
        }
    }

    // 处理活动反馈
    async handleFeedback (ctx, next) {
        const { handleOpinion, feedbackId } = ctx.request.body
        try {
            const res = await handleFeedback({ is_handled: 1, handle_opinion: handleOpinion }, feedbackId)
            if (res.errorFlag) {
                console.error('处理失败，数据库错误', res.message)
                ctx.status = 500
            } else {
                ctx.status = 200
                ctx.body = {
                    hasOk: true,
                    code: 20000,
                    message: '反馈处理成功',
                    data: ''
                }
            }
        } catch (error) {
            ctx.status = 500
            console.error('数据修改失败', error)
            return
        }
    }

    /**
     * 参赛文件上传
     */
    async uploadEntry (ctx, next) {
        const { userAccount, actId } = ctx.request.body
        const entry_path = ctx.state.entry_path
        const { rows } = await getEntryInfo({ user_account: userAccount, act_id: actId })
        console.log(rows.length)
        if (rows.length === 0) {
            // 此用户未在此活动上传过参赛文件，直接创建新数据
            const createRes = await createEntry({ user_account: userAccount, act_id: actId, entry_path })
            if (createRes.errorFlag) {
                console.error('上传失败，数据库新增数据错误', createRes.message)
                ctx.status = 500
            } else {
                ctx.status = 200
                ctx.body = {
                    hasOk: true,
                    code: 20000,
                    message: '文件上传成功',
                    data: {}
                }
            }
        } else {
            // 此用户已经上传过参赛文件，对旧文件进行覆盖
            let oldEntryPath = rows[0].entry_path
            const modifyRes = await modifyEntry(entry_path, userAccount, actId)
            if (modifyRes.errorFlag) {
                console.error('上传失败，数据库错误', modifyRes.message)
                ctx.status = 500
            } else {
                // 寻找旧文件的路径并删除
                const OldAvatarAllPath = path.join(__dirname, `../public/upload/${oldEntryPath}`)
                fs.unlink(OldAvatarAllPath, (err) => {
                    if (err) {
                        // 找不到旧图像路径
                        console.error('旧文件删除失败', err)
                    }
                })
                ctx.status = 200
                ctx.body = {
                    hasOk: true,
                    code: 20000,
                    message: '已覆盖旧文件',
                    data: ''
                }
            }
        }
    }
}

module.exports = new activityController()